package com.sk.helper.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import com.sk.helper.MainActivity;
import com.sk.helper.R;
import com.sk.helper.base.BaseService;
import com.sk.helper.data.FaceButton;
import com.sk.helper.data.Rules;
import com.sk.helper.db.RealmJsonAdapter;
import com.sk.helper.utils.Protocol;
import com.sk.helper.utils.ScreenUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import io.realm.Realm;
import io.realm.RealmResults;

import static java.lang.Thread.sleep;

/*import cn.gavinliu.open.gamepad.helper.R;
import cn.gavinliu.open.gamepad.helper.base.BaseService;
import cn.gavinliu.open.gamepad.helper.data.Rules;
import cn.gavinliu.open.gamepad.helper.db.RealmJsonAdapter;
import cn.gavinliu.open.gamepad.helper.ui.MainActivity;
import cn.gavinliu.open.gamepad.helper.utils.ScreenUtils;
import io.realm.Realm;
import io.realm.RealmResults;*/

/**
 * 连接PC的Service
 * <p/>
 * Created by Gavin on 16-2-19.
 */
public class ConnectionService extends BaseService {

    public static final String ACTION_SHOW_PANEL = "ACTION_SHOW_PANEL";
    public static final String ACTION_HIDE_PANEL = "ACTION_HIDE_PANEL";

    private static final String HEART_BEAT_PACKET = "HEART_BEAT_PACKET";

    private static final String ACTION_GET_RULES = "ACTION_GET_RULES";
    private static final String ACTION_HEART_BEAT = "ACTION_HEART_BEAT";
    private static final String TAG = "ConnectionService-";

    private WindowManager mWM;

    private View mManagerPanel;
    private Button mManagerButton;

    private ConnectionThread thread;
    byte[] key={0,0,0,0,0,0,0,0,0,0,0};

    private int data = -1;


    public Handler socketmHandler;
    Socket inetSocket = null;
    public static int keyState = 0;
    @Override
    public void onCreate() {
        super.onCreate();

        Log.e("---------connection service","--------create-----");
        mWM = (WindowManager) getSystemService(WINDOW_SERVICE);

        new SocketLooperThread().start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, final int startId) {
        String action = intent != null ? intent.getAction() : "";

        if (ACTION_SHOW_PANEL.equals(action) && mManagerButton == null) {
            mManagerButton = new Button(getApplicationContext());
            mManagerButton.setText(getString(R.string.manage));
            mManagerButton.setPadding(0, 0, 0, 0);
            mManagerButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(final View v) {
                    if (mManagerPanel == null) {
                        mManagerPanel = LayoutInflater.from(getApplication()).inflate(R.layout.manager_panel, null, false);
                        WindowManager.LayoutParams layoutParams = createWindowLayoutParams();
                        layoutParams.x = 0;
                        layoutParams.y = 0;
                        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;

                        mWM.addView(mManagerPanel, layoutParams);
                    } else {
                        mManagerPanel.setVisibility(View.VISIBLE);
                    }
                }
            });

            WindowManager.LayoutParams layoutParams = createWindowLayoutParams();
            layoutParams.x = 0;
            layoutParams.y = ScreenUtils.getInstance().getStatusBarHeight();
            layoutParams.width = getResources().getDimensionPixelSize(R.dimen.btn_width);
            layoutParams.height = getResources().getDimensionPixelSize(R.dimen.btn_height);
            mWM.addView(mManagerButton, layoutParams);


        } else if (ACTION_HIDE_PANEL.equals(action)) {
            removeFloatView();
        } else {

            /////skwq
          /*  if (thread == null) {
                thread = new ConnectionThread();
                thread.start();
            }

            notify(getString(R.string.no_connection));*/
        }

        return START_STICKY;
    }

    private void notify(String text) {
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        Notification notification = new Notification.Builder(this)
                .setContentIntent(contentIntent)
                .setContentTitle(getString(R.string.app_name))
                .setTicker(text)
                .setContentText(text)
                .setSmallIcon(R.mipmap.ic_gamepad)
                .setWhen(System.currentTimeMillis())
                .build();

        startForegroundCompat(R.string.app_name, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForegroundCompat(R.string.app_name);

        removeFloatView();
        thread.close();
    }

    private void removeFloatView() {
        if (mManagerPanel != null) {
            mWM.removeView(mManagerPanel);
            mManagerPanel = null;
        }
        if (mManagerButton != null) {
            mWM.removeView(mManagerButton);
            mManagerButton = null;
        }
    }

    private WindowManager.LayoutParams createWindowLayoutParams() {
        WindowManager.LayoutParams windowLayoutParams = new WindowManager.LayoutParams();
        windowLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        windowLayoutParams.format = PixelFormat.RGBA_8888;
        windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; // 不能抢占聚焦点
        windowLayoutParams.flags = windowLayoutParams.flags | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        windowLayoutParams.flags = windowLayoutParams.flags | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        windowLayoutParams.flags = windowLayoutParams.flags | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
        windowLayoutParams.flags = windowLayoutParams.flags | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
        windowLayoutParams.flags = windowLayoutParams.flags | WindowManager.LayoutParams.FLAG_FULLSCREEN;
        windowLayoutParams.flags = windowLayoutParams.flags | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        windowLayoutParams.alpha = 1.0f;
        windowLayoutParams.gravity = Gravity.START | Gravity.TOP;

        return windowLayoutParams;
    }

    private class ConnectionThread extends Thread {

        private final String TAG = "ConnectionThread";

        private ServerSocket server;

        private boolean loop;


        public ConnectionThread() {
            loop = true;
        }

        @Override
        public void run() {
            try {
                server = new ServerSocket(9001);
                while (loop) {
                    Socket socket = server.accept();
                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());

                    byte[] bytes = new byte[1024];
                    int len;
                    StringBuilder builder = new StringBuilder();
                    if ((len = inputStream.read(bytes)) != -1) {
                        builder.append(new String(bytes, 0, len, "UTF-8"));
                    }

                    String action = builder.toString();
                    Log.d(TAG, action);

                    if (ACTION_GET_RULES.equals(action)) {
                        Realm realm = Realm.getDefaultInstance();
                        RealmResults<Rules> ruleList = realm.where(Rules.class).findAll();
                        String json = RealmJsonAdapter.rulesToJsonString(ruleList);
                        realm.close();

                        byte[] jsonBytes = json.getBytes();


                        for (int i = 0; i < jsonBytes.length; ) {
                            int length;

                            if ((jsonBytes.length - i) >= 1024) {
                                length = 1024;
                            } else {
                                length = jsonBytes.length - i;
                            }

                            outputStream.write(jsonBytes, i, length);
                            i = i + length;
                        }

                        Log.d(TAG, json);

                    } else if (ACTION_HEART_BEAT.equals(action)) {
                        outputStream.writeBytes(HEART_BEAT_PACKET);
                    } else {
                        outputStream.writeBytes(HEART_BEAT_PACKET);
                    }

                    outputStream.flush();
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void close() {
            loop = false;

            if (server != null && !server.isClosed()) {
                try {
                    server.close();
                    server = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static final int PRESS = 0;
    static final int SWIPE = 1;
   /* static final int UP = 0;
    static final int DOWN = 1;*/
    int x1 = 320;
    int y1 = 480;
    int x2 = 960;
    int y2 = 480;


    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind called.");

        return new Binder();
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind called.");
        return super.onUnbind(intent);
    }

    String keyValue;
    int keyId;
    int keyId2;
    String AAA = "aaaaaaaaaaaaa";
    String BBB = "bbbbbbbbbbbbbbb";
   // String temp = "";
    public class Binder extends android.os.Binder{
        public void setData(int data,int ddd){
            //Log.e("TAG1","data="+data);

            ConnectionService.this.data = data;
            Log.e("TAG","data="+data+"ddd="+ddd);
            try {
                //这是划动
                // sleep(2000);
             /*   key[0]=SWIPE;
                key[1]=DOWN;
                key[2]=(byte) (x1&0xFF);
                key[3]=(byte) ((x1>>8)&0xFF);
                key[4]=(byte) (y1&0xFF);
                key[5]=(byte) ((y1>>8)&0xFF);
                key[6]=(byte) (x2&0xFF);
                key[7]=(byte) ((x2>>8)&0xFF);
                key[8]=(byte) (y2&0xFF);
                key[9]=(byte) ((y2>>8)&0xFF);

                socketmHandler.sendEmptyMessage(1);
                sleep(2000);
                key[1]=UP;
                socketmHandler.sendEmptyMessage(1);
                */
                //这是点击
//				sleep(2000);
//				key[0]=PRESS;
//				key[1]=DOWN;
//				key[2]=(byte) (x1&0xFF);
//				key[3]=(byte) ((x1>>8)&0xFF);
//				key[4]=(byte) (y1&0xFF);
//				key[5]=(byte) ((y1>>8)&0xFF);
//				socketmHandler.sendEmptyMessage(1);

                Realm realm = Realm.getDefaultInstance();
                RealmResults<Rules> ruleList = realm.where(Rules.class).findAll();

                String json = RealmJsonAdapter.rulesToJsonString(ruleList);
                realm.close();

                byte[] jsonBytes = json.getBytes();

             /*   if (ddd==96){
                    keyValue = "A";
                    keyId = 1;
                }else if (ddd==97){
                    keyValue = "B";
                    keyId = 2;
                }else if (ddd==99)
                {
                    keyValue = "m";
                    x1 = 111;
                    y1=111;

                }*/
               // for (int j = 0; j<ruleList.get(0).getFaceButtons().size();j++){
                   // Log.e("TAG", "----------------------");
                    /*Log.e("TAG", ruleList.get(0).getFaceButtons().get(j).getKey());
                    if (keyValue.equals(ruleList.get(0).getFaceButtons().get(j).getKey())){
                        x1 = ruleList.get(0).getFaceButtons().get(j).getX();
                        y1 = ruleList.get(0).getFaceButtons().get(j).getY();
                    }*/
                  //  keygameButton = ruleList.get(0).getFaceButtons().get(j);

               // }

               // for (int i = 0; i < jsonBytes.length; i++) {
                   /* int length;
                    if ((jsonBytes.length - i) >= 1024) {
                        length = 1024;
                    } else {
                        length = jsonBytes.length - i;
                    }
                   // outputStream.write(jsonBytes, i, length);
                    i = i + length;*/
                //}
               /* Log.e(TAG, json);
                Log.e(TAG, "----------------");*/
              /*  if (ddd==96){
                    keyValue = "A";
                    keyId = 1;
                }else if (ddd==97){
                    keyValue = "B";
                    keyId = 2;
                }else if (ddd==99)
                {
                    keyValue = "m";
                    x1 = 111;
                    y1=111;

                }*/


                if(data==Protocol.KEYDOWN) {
                    Log.e("TAG", "-------ddd--="+ddd);

                      key[0] = (byte) (keyId & 0xFF);
                        key[1] = Protocol.KEYDOWN;
                        key[2] = (byte) (x1 & 0xFF);
                        key[3] = (byte) ((x1 >> 8) & 0xFF);
                        key[4] = (byte) (y1 & 0xFF);
                        key[5] = (byte) ((y1 >> 8) & 0xFF);
                       // temp = AAA;

                    socketmHandler.sendEmptyMessage(1);
                  //  Thread.sleep(10);
                }else {

                        key[0] = (byte) (keyId & 0xFF);
                        key[1] = Protocol.KEYUP;
                        key[2] = (byte) (x1 & 0xFF);
                        key[3] = (byte) ((x1 >> 8) & 0xFF);
                        key[4] = (byte) (y1 & 0xFF);
                        key[5] = (byte) ((y1 >> 8) & 0xFF);

                    socketmHandler.sendEmptyMessage(1);
                    //Thread.sleep(10);
                }
                Thread.sleep(60);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

   /* private Socket RequestSocket(InetAddress host, int port) throws IOException {
        Socket socket = new Socket(host,port);
        return socket;
    }

    private void SendMsg(Socket socket,String msg) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write(msg);
        writer.flush();
    }

    private String ReceiveMsg(Socket socket) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String Msg = reader.readLine();
        return Msg;
    }*/
    class SocketLooperThread extends Thread {

        public void run() {
            Looper.prepare();
            Log.e(TAG,"SocketLooperThread");
            socketmHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // process incoming messages here
                    if(msg.what == 1)
                    {
                        try {
                           // Log.e(TAG,"key-==" + key);
                            //inetSocket = RequestSocket(InetAddress.getLocalHost(), 10080);
                           // SendMsg(inetSocket,temp);
                            //String sss = ReceiveMsg(inetSocket);
//                            if ("success".equals(sss)){
//
//                            }


                                inetSocket = new Socket(InetAddress.getLocalHost(), 10080);
                           // Log.e(TAG,"0---==" + inetSocket.isInputShutdown());
                            inetSocket.getOutputStream().write(key);
                            inetSocket.getOutputStream().flush();

                            inetSocket.getOutputStream().close();
                            inetSocket.close();



                        /*    //获取输出流
                            OutputStream ops = inetSocket.getOutputStream();
                            ObjectOutputStream oos = new ObjectOutputStream(ops);
                            //使用对象流将user对象发送到服务器端
                            oos.writeObject(keygameButton);
                            oos.flush();*/
                            //获取服务器端响应消息
                       /*     InputStream ips = inetSocket.getInputStream();
                            DataInputStream dis = new DataInputStream(ips);
                            String str = dis.readUTF();
                            System.out.println(str);*/
                            //释放资源
                            //dis.close();
                          //  oos.close();
                          //  inetSocket.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            };
            Looper.loop();
        }
    }
}
